# utils/logger.py

import logging
import os
import sys

# Define the log directory relative to the main script
log_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), '../../../logs')

# Ensure the log directory exists
os.makedirs(log_dir, exist_ok=True)

# Define the log file path
LOG_FILE_PATH = os.path.join(log_dir, 'log.txt')

def set_logger(log_file_path=LOG_FILE_PATH):
    # Configure the logger
    logger = logging.getLogger('my_logger')
    logger.setLevel(logging.INFO)

    # Check if the LOG_FILE_PATH is valid
    if not os.path.exists(log_file_path):
        # Create the log file if it doesn't exist
        with open(log_file_path, 'w') as f:
            # This will create the file if it doesn't exist
            pass
    # Check if the log file is writable
    if not os.access(log_file_path, os.W_OK):
        raise PermissionError(f"Log file {log_file_path} is not writable.")
    # Check if the log file is a directory
    if os.path.isdir(log_file_path):
        raise IsADirectoryError(f"Log file {log_file_path} is a directory.")

    # Avoid duplicate handlers if the logger is already configured
    if not logger.handlers:
        # Create handlers
        file_handler = logging.FileHandler(log_file_path)
        console_handler = logging.StreamHandler()

        # Set level for handlers
        file_handler.setLevel(logging.INFO)
        console_handler.setLevel(logging.INFO)

        # Create a formatter and set it for both handlers
        formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s',
                                      datefmt='%d-%b-%y %H:%M:%S')
        file_handler.setFormatter(formatter)
        console_handler.setFormatter(formatter)

        # Add handlers to the logger
        logger.addHandler(file_handler)
        logger.addHandler(console_handler)

    # Redirect unhandled exceptions to the logger
    def handle_exception(exc_type, exc_value, exc_traceback):
        if issubclass(exc_type, KeyboardInterrupt):
            # Let the program exit gracefully on KeyboardInterrupt
            sys.__excepthook__(exc_type, exc_value, exc_traceback)
            return
        logger.error("Unhandled exception",
                     exc_info=(exc_type, exc_value, exc_traceback))

    sys.excepthook = handle_exception

    return logger
